package com.softserve.crazymachine.requestbuilder;


import java.util.HashMap;
import java.util.Map;

import com.softserve.crazymachine.request.Request;

/**
 * @author Mykhailo Tys
 * 
 */
public class ConcreteRequestBuilder extends RequestBuilder {

	
	/**
	 * @param request
	 * @param req takes string view of request
	 * @return array of lines of request
	 */
	private String[] getHeadersArray(Request request, String req) {
		String[] array = null;
		if (request.getRequestType().equals("GET")) {
			array = req.split("\n");
		} else if (request.getRequestType().equals("POST")) {
			String[] bufArray = req.split("\n");
			array = new String[bufArray.length - 2];
			for (int i = 0; i < array.length; i++) {
				array[i] = bufArray[i];
			}
		}
		return array;
	}

	/**
	 * @param req
	 *            takes string view of request
	 * @return parameters for POST request
	 */
	private String getParams(String req) {
		int number = req.indexOf("\n\n");
		return req.substring(number + 1);
	}

	@Override
	public void parse(byte[] bites) {
		// TODO Auto-generated method stub
		request = new Request();
		String req = new String(bites);
		int r = req.indexOf(" ");
		String firstWord = req.substring(0, r);
		if (firstWord.equals("GET")) {
			request.setRequestType("GET");
			String url = req.substring(r + 1, req.indexOf(" ", r + 1));
			request.setResource(url);
			String[] headers = getHeadersArray(request, req);
			Map<String, String> map = new HashMap<String, String>();
			for (int i = 1; i < headers.length; i++) {
				if (headers[i].equals("\n\n")) {
					break;
				} else {
					int number = headers[i].indexOf(":");
					String key = headers[i].substring(0, number);
					String value = headers[i].substring(number + 2,
							headers[i].length());
					map.put(key, value);
				}
			}
			request.setHeadersMap(map);
		} else if (firstWord.equals("POST")) {
			request.setRequestType("POST");
			String url = req.substring(r + 1, req.indexOf(" ", r + 1));
			request.setResource(url);
			String[] headers = getHeadersArray(request, req);
			Map<String, String> map = new HashMap<String, String>();
			for (int i = 1; i < headers.length; i++) {
				if (headers[i].equals("\n\n")) {
					break;
				} else {
					int number = headers[i].indexOf(":");
					String key = headers[i].substring(0, number);
					String value = headers[i].substring(number + 2,
							headers[i].length());
					map.put(key, value);
				}
			}

			map.put("Parameters:", getParams(req));
			request.setHeadersMap(map);
		}
	}

	
}
